'use client';

import { useState } from 'react';
import { City } from '@/types/weather';

export default function CitySearch() {
    const [query, setQuery] = useState('');
    const [results, setResults] = useState<City[]>([]);

    const handleSearch = async (value: string) => {
        setQuery(value);
        if (value.length < 2) return;

        try {
            const response = await fetch(`/api/cities/search?q=${value}`);
            const data = await response.json();
            setResults(data);
        } catch (error) {
            console.error('Error searching cities:', error);
        }
    };

    return (
        <div className="space-y-4">
            <input
                type="text"
                value={query}
                onChange={(e) => handleSearch(e.target.value)}
                placeholder="搜索城市..."
                className="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />

            {results.length > 0 && (
                <ul className="bg-white rounded-lg shadow-lg divide-y">
                    {results.map((city) => (
                        <li
                            key={city.id}
                            className="px-4 py-3 hover:bg-gray-50 cursor-pointer"
                        >
                            {city.name}, {city.country}
                        </li>
                    ))}
                </ul>
            )}
        </div>
    );
}